<?php
/**
 * Crontab file
 *
 * this file can be executed in 2 ways:
 *  1. using a web cron
 *  2. using a unix cron
 * in both cases a key is required to execute the script
 * @author University of London Computer Centre
 * @version 1.3.0 - Release Candidate 1
 * @package ArchivePress
 */


// I check if the plugin is active before
if(get_option(WP_ARCHIVEPRESS_PREFIX . "isRunning") == "yes" )  {
	global $ArchivePressLog;
	global $ArchivePress;
	// get the secret key from wp options
	$savedKey = get_option(WP_ARCHIVEPRESS_PREFIX . "cronKey");
	$userKey = "";
	// get the key provided as script argument
	if(get_option(WP_ARCHIVEPRESS_PREFIX . "cronType") == ArchivePressOptions::CRON_WEBCRON) {
		// web cron
		$ArchivePressLog->logIt(ArchivePressLog::LOG_DEBUG,__("Cron type = WEB",ARCHIVEPRESS));
		if(isset($_GET[WP_ARCHIVEPRESS_PREFIX . "key"])) {
			$userKey = $_GET[WP_ARCHIVEPRESS_PREFIX . "key"];
		}
	} else if(get_option(WP_ARCHIVEPRESS_PREFIX . "cronType") == ArchivePressOptions::CRON_UNIXCRON) {
		// unix cron
		$ArchivePressLog->logIt(ArchivePressLog::LOG_DEBUG,__("Cron type = UNIX",ARCHIVEPRESS));
		if(isset($argv[1])) {
			$userKey = $argv[1];
		}
	} else {
		// don't execute the script if the cron is setted to CRON_WPCRON (it is already executed BY WORDPRESS!)
		$ArchivePressLog->logIt(ArchivePressLog::LOG_DEBUG,__("The cron job has not been executed because the cron type is the WordPress one",ARCHIVEPRESS));
	}
	if($savedKey == $userKey) {
		// esecute script
		$ArchivePressLog->logIt(ArchivePressLog::LOG_DEBUG,__("Cron job started successfully.",ARCHIVEPRESS));

		// get active feeds
		$activeFeeds = array();
		$activeFeeds = $ArchivePress->getFeeds(true,false);

		foreach($activeFeeds as $feed){
			// check if I have to fetch the feed
			if( (time() - strtotime($feed["last_update"])) >= (int)$feed["interval"] ) {
				if($feed["is_comment"] == "no"){
				    // fetch feed and its comment feeds
					$ArchivePressLog->logIt(ArchivePressLog::LOG_BASIC,sprintf(__("Fetching feed %s (%s)> posts added: %d ",ARCHIVEPRESS),$feed["name"],$feed["url"],$ArchivePress->fetchFeed($feed)));
				    $ArchivePressLog->logIt(ArchivePressLog::LOG_BASIC,sprintf(__("Fetching feed %s (%s)> posts added: %d ",ARCHIVEPRESS),$feed["name"],$feed["url"],$ArchivePress->fetchFeedComments($feed["id"], true)));
				}else{
					// do nothing
				}
			}
		}
	} else if(get_option(WP_ARCHIVEPRESS_PREFIX . "cronType") != ArchivePressOptions::CRON_WPCRON) {
		$ArchivePressLog->logIt(ArchivePressLog::LOG_DEBUG,__("Feed fetching not started because the provided key is wrong",ARCHIVEPRESS));
	}
}
?>